package com.legolas.consumer.service.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.stereotype.Service;

import javax.jms.*;

@Service
public class QueueConsumer {
    String text = "error";
    //a、b、c三台服务器都可以作为服务器，向消费者提供服务
    private static final String slv_url = "failover:(tcp://127.0.0.1:61616,tcp://127.0.0.1:61617,tcp:127.0.0.1:61618)?randomize=true";

    private static final String url = "tcp://127.0.0.1:61616";

    public String consum(String queueName) throws JMSException {

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        Connection connection = connectionFactory.createConnection();

        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建一个目标
        Destination destination = session.createQueue(queueName);

        //创建一个消费者
        MessageConsumer consumer = session.createConsumer(destination);

        //创建一个监听器
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    text = textMessage.getText();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        return text;
        //关闭连接
        // connection.close();
    }


}
